import { useState, useEffect, useCallback, useMemo } from 'react';
import { meituanConfigService, meituanGroupService, commonService } from '../services/base';

/**
 * 美团数据管理Hook
 * 提供集中化的状态管理和数据获取
 */
export const useMeituanData = () => {
  const [stores, setStores] = useState([]);
  const [meituanConfigs, setMeituanConfigs] = useState([]);
  const [meituanGroups, setMeituanGroups] = useState([]);
  const [orders, setOrders] = useState([]);
  
  const [loading, setLoading] = useState({
    stores: false,
    configs: false,
    groups: false,
    orders: false,
  });
  
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  /**
   * 获取门店列表
   */
  const fetchStores = useCallback(async (params = {}) => {
    setLoading(prev => ({ ...prev, stores: true }));
    setError(null);
    
    try {
      const response = await commonService.getStores(params);
      const list = Array.isArray(response) ? response : response.list || [];
      setStores(list);
      return list;
    } catch (error) {
      setError(error.message);
      console.error('获取门店列表失败:', error);
      return [];
    } finally {
      setLoading(prev => ({ ...prev, stores: false }));
    }
  }, []);

  /**
   * 获取美团配置列表
   */
  const fetchMeituanConfigs = useCallback(async (params = {}) => {
    setLoading(prev => ({ ...prev, configs: true }));
    setError(null);
    
    try {
      const response = await meituanConfigService.getList(params);
      const list = Array.isArray(response) ? response : response.list || [];
      setMeituanConfigs(list);
      return list;
    } catch (error) {
      setError(error.message);
      console.error('获取美团配置失败:', error);
      return [];
    } finally {
      setLoading(prev => ({ ...prev, configs: false }));
    }
  }, []);

  /**
   * 获取团购活动列表
   */
  const fetchMeituanGroups = useCallback(async (params = {}) => {
    setLoading(prev => ({ ...prev, groups: true }));
    setError(null);
    
    try {
      const response = await meituanGroupService.getList(params);
      const list = Array.isArray(response) ? response : response.list || [];
      const total = response.total || list.length;
      
      setMeituanGroups(list);
      setPagination(prev => ({
        ...prev,
        total,
        current: params.page || 1,
        pageSize: params.page_size || 10,
      }));
      
      return { list, total };
    } catch (error) {
      setError(error.message);
      console.error('获取团购活动失败:', error);
      return { list: [], total: 0 };
    } finally {
      setLoading(prev => ({ ...prev, groups: false }));
    }
  }, []);

  /**
   * 获取订单列表
   */
  const fetchOrders = useCallback(async (params = {}) => {
    setLoading(prev => ({ ...prev, orders: true }));
    setError(null);
    
    try {
      const isGroupOrder = params.isGroup !== false;
      const service = isGroupOrder ? meituanGroupService : meituanConfigService;
      const endpoint = isGroupOrder ? '/order' : '/order';
      
      const response = await service.getOrderList(params);
      const list = Array.isArray(response) ? response : response.list || [];
      const total = response.total || list.length;
      
      setOrders(list);
      setPagination(prev => ({
        ...prev,
        total,
        current: params.page || 1,
        pageSize: params.page_size || 10,
      }));
      
      return { list, total };
    } catch (error) {
      setError(error.message);
      console.error('获取订单失败:', error);
      return { list: [], total: 0 };
    } finally {
      setLoading(prev => ({ ...prev, orders: false }));
    }
  }, []);

  /**
   * 同步订单数据
   */
  const syncOrders = useCallback(async (params = {}) => {
    setLoading(prev => ({ ...prev, orders: true }));
    setError(null);
    
    try {
      const response = await meituanGroupService.syncOrders(params);
      const count = response.count || 0;
      
      // 同步完成后重新获取订单列表
      if (count > 0) {
        await fetchOrders(params);
      }
      
      return count;
    } catch (error) {
      setError(error.message);
      console.error('同步订单失败:', error);
      return 0;
    } finally {
      setLoading(prev => ({ ...prev, orders: false }));
    }
  }, [fetchOrders]);

  /**
   * 处理订单
   */
  const processOrder = useCallback(async (orderId, status, remark = '') => {
    setLoading(prev => ({ ...prev, orders: true }));
    setError(null);
    
    try {
      const data = { id: orderId, status, remark };
      await meituanGroupService.processOrder(data);
      
      // 更新本地订单状态
      setOrders(prev => 
        prev.map(order => 
          order.id === orderId 
            ? { ...order, process_status: getProcessStatus(status), is_processed: 1 }
            : order
        )
      );
      
      return true;
    } catch (error) {
      setError(error.message);
      console.error('处理订单失败:', error);
      return false;
    } finally {
      setLoading(prev => ({ ...prev, orders: false }));
    }
  }, []);

  /**
   * 使用团购券
   */
  const useVoucher = useCallback(async (orderId) => {
    setLoading(prev => ({ ...prev, orders: true }));
    setError(null);
    
    try {
      await meituanGroupService.useVoucher(orderId);
      
      // 更新本地订单状态
      setOrders(prev => 
        prev.map(order => 
          order.id === orderId 
            ? { ...order, is_used: 1 }
            : order
        )
      );
      
      return true;
    } catch (error) {
      setError(error.message);
      console.error('使用团购券失败:', error);
      return false;
    } finally {
      setLoading(prev => ({ ...prev, orders: false }));
    }
  }, []);

  /**
   * 获取指定门店的美团配置
   */
  const getStoreMeituanConfig = useCallback((storeId) => {
    return meituanConfigs.find(config => config.store_id === storeId);
  }, [meituanConfigs]);

  /**
   * 获取指定门店的团购活动
   */
  const getStoreMeituanGroups = useCallback((storeId) => {
    return meituanGroups.filter(group => group.store_id === storeId);
  }, [meituanGroups]);

  /**
   * 获取指定门店的订单
   */
  const getStoreOrders = useCallback((storeId) => {
    return orders.filter(order => order.store_id === storeId);
  }, [orders]);

  /**
   * 获取订单统计信息
   */
  const getOrderStats = useCallback(() => {
    const stats = {
      total: orders.length,
      pending: 0,
      accepted: 0,
      rejected: 0,
      completed: 0,
      used: 0,
    };

    orders.forEach(order => {
      if (order.process_status === 'pending') stats.pending++;
      if (order.process_status === 'accepted') stats.accepted++;
      if (order.process_status === 'rejected') stats.rejected++;
      if (order.process_status === 'completed') stats.completed++;
      if (order.is_used === 1) stats.used++;
    });

    return stats;
  }, [orders]);

  /**
   * 重置错误状态
   */
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  /**
   * 重置所有数据
   */
  const resetData = useCallback(() => {
    setStores([]);
    setMeituanConfigs([]);
    setMeituanGroups([]);
    setOrders([]);
    setError(null);
    setPagination({ current: 1, pageSize: 10, total: 0 });
  }, []);

  /**
   * 预加载所有基础数据
   */
  const preloadData = useCallback(async () => {
    try {
      await Promise.all([
        fetchStores(),
        fetchMeituanConfigs(),
        fetchMeituanGroups(),
      ]);
    } catch (error) {
      console.error('预加载数据失败:', error);
    }
  }, [fetchStores, fetchMeituanConfigs, fetchMeituanGroups]);

  // 计算属性
  const storeOptions = useMemo(() => 
    stores.map(store => ({ value: store.id, label: store.name }))
  , [stores]);

  const meituanConfigOptions = useMemo(() => 
    meituanConfigs.map(config => ({ 
      value: config.id, 
      label: `${config.store_name} - ${config.poi_id}` 
    }))
  , [meituanConfigs]);

  const meituanGroupOptions = useMemo(() => 
    meituanGroups.map(group => ({ 
      value: group.id, 
      label: group.title 
    }))
  , [meituanGroups]);

  return {
    // 数据
    stores,
    meituanConfigs,
    meituanGroups,
    orders,
    
    // 状态
    loading,
    error,
    pagination,
    
    // 计算属性
    storeOptions,
    meituanConfigOptions,
    meituanGroupOptions,
    
    // 方法
    fetchStores,
    fetchMeituanConfigs,
    fetchMeituanGroups,
    fetchOrders,
    syncOrders,
    processOrder,
    useVoucher,
    getStoreMeituanConfig,
    getStoreMeituanGroups,
    getStoreOrders,
    getOrderStats,
    clearError,
    resetData,
    preloadData,
  };
};

/**
 * 获取处理状态映射
 */
const getProcessStatus = (status) => {
  const mapping = {
    1: 'accepted',
    2: 'rejected',
    3: 'completed',
  };
  return mapping[status] || 'pending';
};

/**
 * 使用缓存的Hook
 */
export const useCachedData = (key, fetcher, deps = []) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      // 尝试从本地存储获取缓存
      const cached = localStorage.getItem(key);
      if (cached) {
        const { data: cachedData, timestamp } = JSON.parse(cached);
        const cacheAge = Date.now() - timestamp;
        
        // 缓存有效期：5分钟
        if (cacheAge < 5 * 60 * 1000) {
          setData(cachedData);
          return cachedData;
        }
      }

      // 获取新数据
      const newData = await fetcher();
      
      // 缓存新数据
      localStorage.setItem(key, JSON.stringify({
        data: newData,
        timestamp: Date.now(),
      }));
      
      setData(newData);
      return newData;
    } catch (error) {
      setError(error.message);
      console.error(`获取${key}失败:`, error);
      return null;
    } finally {
      setLoading(false);
    }
  }, [key, fetcher]);

  // 清除缓存
  const clearCache = useCallback(() => {
    localStorage.removeItem(key);
    setData(null);
  }, [key]);

  // 监听依赖变化
  useEffect(() => {
    fetchData();
  }, [fetchData, ...deps]);

  return {
    data,
    loading,
    error,
    refetch: fetchData,
    clearCache,
  };
};